package demo1;

public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key,int val){
            this.key=key;
            this.val=val;
        }
    }
    public Node[] array;
    public int UsedSize;
    public static final float DEFAULT_LOAD_FACTOR=0.75f;

    public HashBuck(){
        array=new Node[10];
    }
    public void put(int key,int val){
        int index=key%array.length;
        Node cur=array[index];
        while (cur!=null){
            if (cur.key==key){
                cur.val=val;
            }
            cur=cur.next;
        }
        //前面的数据没找到，更新不了，就要添加新的元素
        Node node=new Node(key,val);
        node.next=array[index];
        array[index]=node;

        if(doLoadFactor() > DEFAULT_LOAD_FACTOR) {
            //扩容！！
            //array = Arrays.copyOf(array,2*array.length);error
            resize();
        }

    }

    private float doLoadFactor() {
        return UsedSize*1.0f/array.length;
    }

    private void resize() {
        Node[] newArray = new Node[2*array.length];
        //遍历原来的数组
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            //遍历每个数组元素(链表)
            while (cur != null) {
                Node tmp = cur.next;
                int newIndex = cur.key % newArray.length;//新的数组下标
                //采用头插法 插入到新数组的 newIndex下标
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = tmp;
            }
        }
        array = newArray;
    }


}
